package filefinder.finders;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Finder implementation using regular expressions
 * 
 * @author denist
 * 
 */

public class GrepFinder implements Finder {

	Pattern compile(String pat) {
		Pattern pattern = null;
		try {
			pattern = Pattern.compile(pat);
		} catch (PatternSyntaxException x) {
			x.printStackTrace();
		}
		return pattern;
	}

	public void find(File file, String toFind, List list) {
		BufferedReader reader = null;
		try {
			Matcher pm = null;
			Pattern pattern = compile(toFind);
			if (pattern==null){
				return;
			}
			reader = new BufferedReader(new FileReader(file));
			String line;

			while ((line = reader.readLine()) != null) {
				pm = pattern.matcher(line);
				if (pm.find()) {
					synchronized (list) {
						list.add(file.getAbsolutePath());
					}
					break;
				}
			}
		} catch (FileNotFoundException e) {
			System.out.println("Cannot open the file due to");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Cannot read the file due to");
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					System.out.println("Cannot close the file due to");
					e.printStackTrace();
				}
			}
		}
	}
}